<template>
  <div>
    <template v-for="(fileType, fileIndex) in industryFiles">
      <div :key="fileIndex" :style="{marginBottom: fileIndex === industryFiles.length-1 ? 0 : '18px'}" :class="{'mobile-certificate-group':showMobilePage}" class="certificate-group">
        <el-select
          v-model="fileType['key']"
          placeholder="字段"
          popper-class="width120 global-select-down"
          name="sortField"
          style="position: relative"
          @visible-change="onSelectVisibleChange($event, fileType['key'])"
          @clear="fileType['key'] = 'unsetKey'"
          @change="onFileChange($event, fileIndex)">
          <el-option :value="'unsetKey'" label="请选择证件类型" />
          <el-option
            v-for="certificate in certificateAttachment"
            :key="certificate.value"
            :label="certificate.label"
            :value="certificate.value"
            :disabled="setDisabledOption(certificate.value)"
          />
        </el-select>
        <div v-show="fileType['showTip']" class="select-err">请选择证件类型</div>
        <el-form-item
          :rules="rules[`merchandiseInfos${fileType['key']}`]"
          :prop="'merchandiseInfos.' + curIndex + '.' + fileType['key']"
          class="normal-form-item">
          <attachment-picker
            v-model="certificateData[fileType['key']]"
            :index="fileIndex"
            :module-name="'merchandiseInfos.' + curIndex + '.' + fileType['key']"
            :date-verify="false"
            :is-verify="fileType['key'] !== 'unsetKey'"
            is-show-date-pick
            key-field="attachment"
            date-field="effectiveDate"
            @complateSetData="validateField('merchandiseInfos.' + curIndex + '.'+ fileType['key'] + '.attachment')"
            @removeFile="validateField('merchandiseInfos.' + curIndex + '.' + fileType['key'] + '.attachment')"
          />
          <div v-if="fileType['key'] === 'unsetKey'" class="upload-mask" @click="onBeforeSelectType(fileIndex)" />
        </el-form-item>
        <div class="delete-btn" @click="onCertificateDel(fileIndex)">删除</div>
        <div v-show="industryFiles.length === fileIndex + 1 && industryFiles.length < certificateAttachment.length" class="add-btn" @click="onCertificateAdd">添加证件<i class="el-icon-plus" style="margin-left: 8px"/></div>
      </div>
    </template>
    <div v-show="!industryFiles.length" class="add-btn" @click="onCertificateAdd">添加证件<i class="el-icon-plus" style="margin-left: 8px"/></div>
  </div>
</template>

<script>
import { certificateAttachment } from '../../module/options';
import AttachmentPicker from './attachmentPicker';
import { mapState } from 'vuex';
export default {
  name: 'SelectCertificate',
  components: {
    AttachmentPicker
  },
  props: {
    curIndex: {
      type: Number,
      default: 0
    },
    rules: {
      type: Object,
      default: () => {
        return null;
      }
    },
    certificateData: {
      type: Object,
      default: () => {
        return null;
      }
    }
  },
  data() {
    return {
      certificateAttachment,
      curKey: '',
      industryFiles: []
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    })
  },
  watch: {
    certificateData: {
      handler(data) {
        this.setIndustryFiles(data);
      },
      immediate: true
    }
  },
  methods: {
    setIndustryFiles(data) {
      const selectCertificateKeys = [
        'inspectionReport',
        'cccCertificate',
        'businessPermit',
        'recordAttachment',
        'hygienicLicense',
        'trustAgreement',
        'distributionLicense',
        'productionLicense',
        'customsDeclaration',
        'accountOpeningCertificate',
        'otherAttachment'
      ];
      selectCertificateKeys.forEach(key => {
        if (data[key] && data[key].attachment.length) {
          this.industryFiles.push({ key, showTip: false });
        }
      });
      !this.industryFiles.length && this.industryFiles.push({ key: 'unsetKey', showTip: false });
    },
    onSelectVisibleChange(state, key) {
      this.curKey = state ? key : '';
    },
    onFileChange(item, index) {
      if (item && item !== 'unsetKey') {
        this.industryFiles[index].showTip = false;
      }
      this.clearAttachment(this.curKey);
    },
    // 重置附件内容
    clearAttachment(key) {
      if (key !== 'unsetKey') {
        const curCertificate = this.certificateData[key];
        curCertificate.attachment = [];
        curCertificate.effectiveDate = '';
      }
    },
    onCertificateAdd() {
      const newCertificate = { key: 'unsetKey', showTip: false };
      this.industryFiles.push(newCertificate);
    },
    onCertificateDel(index) {
      const delKey = this.industryFiles[index].key;
      this.industryFiles.splice(index, 1);
      this.clearAttachment(delKey);
    },
    validateField(ruleName) {
      this.$emit('completeSetData', ruleName);
    },
    setDisabledOption(key) {
      if (key === 'unsetKey') return;
      for (let i = 0; i < this.industryFiles.length; i++) {
        if (this.industryFiles[i].key === key) {
          return true;
        }
      }
    },
    // 未选择证件类型禁止上传附件
    onBeforeSelectType(index) {
      this.industryFiles[index].showTip = true;
    }
  }
};
</script>

<style scoped lang="scss">
.certificate-group {
  display: flex;
  align-items: flex-start;
  .select-err {
    color: #F56C6C;
    font-size: 12px;
    line-height: 1;
    position: absolute;
    margin-top: 35px;
    margin-left: 12px;
    left: 0;
  }
  ::v-deep .el-input__inner {
    width: 145px !important;
  }
  ::v-deep .up-attachment {
    width: 240px !important;
    margin-left: 12px;
    display: inherit;
  }
  ::v-deep .date-picker {
    height: 32px;
    display: flex;
    align-items: center;
  }
}
.delete-btn {
  margin-left: 6px;
  cursor: pointer;
  color: #192452;
  font-size: 14px;
  font-weight: bold;
  height: 32px;
  line-height: 32px;
}
.add-btn {
  margin-left: 16px;
  color: #406EFF;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  height: 32px;
  line-height: 32px;
}
.upload-mask {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  cursor: pointer;
  z-index: 6;
}
.mobile-certificate-group {
  flex-wrap: wrap;
  ::v-deep .el-input__inner {
    width: 100% !important;
  }
  .attachment-picker-wrap {
    flex-wrap: wrap;
    ::v-deep {
      .up-attachment, .date-picker {
        margin-left: 0;
      }
      .up-attachment {
        margin: 16px 0;
      }
      .date-picker {
        width: 100%;
      }
    }
  }
}
</style>
